package com.lgedu.list;

/**
 * @Author: Hugh
 * @Date: 2020/11/29
 */
public class SingleLinkedList {

    //初始化头节点

    private Node head = new Node(0, "");

    /** * 添加节点：从头插入 * * @param node */
    public void addNode(Node node) {
        //从头插入
        Node tmp = head;
        while (true) {

            //到尾节点
            if (tmp.next == null) {
                break;
            }
            //后移一个节点 tmp = tmp.next;

    }

    tmp.next = node;
    }

    public void addByIdOrder(Node node){
        //从头插入
        Node tmp = head;
        while (true) {
            //到尾节点
            if (tmp.next == null) {
                break;
            } //节点存在
            if (tmp.next.id == node.id) {
                break;
            }

        if (tmp.next.id > node.id) {
            break;
        }
        tmp = tmp.next;

        }

        //交换位置
        node.next = tmp.next;
        tmp.next = node;

    }

    //遍历链表
    public void showList() {

        //空链表
        if (head.next == null) {

            System.out.println("链表为空");

            return;
        }

        Node temp = head.next; while (true) {

            if (temp == null) {
                return;
            }
            System.out.println(temp);
            //指针下移
            temp = temp.next;

        }

    }
    public static void main(String[] args) { Node n1=new Node(1,"张飞");

        Node n2=new Node(2,"关羽");

        Node n3=new Node(3,"赵云");

        Node n4=new Node(4,"黄忠");

        Node n5=new Node(5,"马超");

        SingleLinkedList sll=new SingleLinkedList(); sll.addByIdOrder(n4); sll.addByIdOrder(n5); sll.addByIdOrder(n1); sll.addByIdOrder(n2); sll.addByIdOrder(n3);

        sll.showList();

    }
}
